package com.hsy.linemoney.application;

import android.app.Activity;
import android.app.ActivityManager;
import android.app.AlarmManager;
import android.app.PendingIntent;
import android.content.Context;
import android.content.Intent;

import com.hsy.linemoney.BuildConfig;
import com.hsy.linemoney.apiservice.LineMoneyContext;
import com.hsy.linemoney.common.GlobalLoadingPopup;
import com.hsy.linemoney.common.PasswordSaver;
import com.hsy.linemoney.utils.ToastUtil;

import org.simple.eventbus.EventBus;

import java.util.List;

/**
 * Created by Administrator on 2016/6/28.
 */
public class Application extends android.app.Application {

    private static Application mInstance;

    @Override
    public final void onCreate() {
        super.onCreate();
        onCreateWithPid(android.os.Process.myPid());
    }

    protected void onCreateWithPid(int pid) {
        if (BuildConfig.APPLICATION_ID.equals(getProcessName(this, pid))) {
            onCreateThis();
        }
    }

    protected void onCreateThis() {
        PasswordSaver.init(this);
        ToastUtil.init(this);
        LineMoneyContext.init(this);
        mInstance = this;


//        Thread.setDefaultUncaughtExceptionHandler(restartHandler); // 程序崩溃时触发线程
    }

    public Thread.UncaughtExceptionHandler restartHandler = new Thread.UncaughtExceptionHandler() {
        @Override
        public void uncaughtException(Thread thread, Throwable ex) {
            Intent intent = new Intent();
            intent.setClassName("com.hsy.linemoney", "com.hsy.linemoney.modules.lanuch.SplashActivity");
            intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
            startActivity(intent);
            System.exit(0);
            thread.interrupt();
//            throw new RuntimeException(ex);
        }
    };

    public static String getProcessName(Context cxt, int pid) {
        ActivityManager am = (ActivityManager) cxt.getSystemService(Context.ACTIVITY_SERVICE);
        List<ActivityManager.RunningAppProcessInfo> runningApps = am.getRunningAppProcesses();
        if (runningApps == null) {
            return null;
        }
        for (ActivityManager.RunningAppProcessInfo procInfo : runningApps) {
            if (procInfo.pid == pid) {
                return procInfo.processName;
            }
        }
        return null;
    }

    public static Application getInstance() {
        return mInstance;
    }

    public synchronized void showProgressDialog(Activity activity) {
        if (!GlobalLoadingPopup.isShowing()) {
            Intent intent = new Intent(getApplicationContext(), GlobalLoadingPopup.class);
            activity.startActivity(intent);
        }
    }

    public void hideProgressDialog() {
        GlobalLoadingPopup.hide();
    }

    public boolean isProgressDialogShowing() {
        return GlobalLoadingPopup.isShowing();
    }
}
